import { ipcMain } from 'electron'
import * as cheerio from 'cheerio'
import ejs from 'ejs'
import fs from 'fs'
import prettier from 'prettier'

export const setupDomToTableDetailHandlers = () => {
  ipcMain.handle('dom-to-table-detail', (_event, richText: any) => {
    return new Promise(async (resolve) => {
      const tableConfig = getTableConfig(richText)
      console.log(tableConfig)
      const tableRes = await renderDescriptions(tableConfig)
      console.log(tableRes)
      resolve(tableRes)
    })
  })
}

const renderDescriptions = (tableConfig: any) => {
  return new Promise((resolve, reject) => {
    fs.readFile(
      './src/main/handlers/domToTableDetail/descriptions.ejs',
      'utf8',
      (err, template) => {
        if (err) {
          reject(err)
          console.error('Error reading template:', err)
          return
        }

        // 渲染模板，并传递变量
        const renderedTemplate = ejs.render(template, {
          tableConfig
        })

        const formattedTemplate = prettier.format(renderedTemplate, {
          parser: 'vue',
          printWidth: 120,
          tabWidth: 4,
          useTabs: true
        })

        resolve(formattedTemplate)
      }
    )
  })
}

const getTableConfig = (cleanHtml) => {
  const $ = cheerio.load(cleanHtml)
  const tableConfig: any = {
    columns: []
  }

  // 查找 .layui-table 下的所有 tr
  $('table tr').each((rowIndex, row) => {
    const $row = $(row)
    const rowData: any[] = []

    // 获取当前行的所有 th 和 td
    const cells = $row.find('th, td').toArray()

    for (let i = 0; i < cells.length; i++) {
      const cell = cells[i]
      const $cell = $(cell)
      const cellType = cell.tagName.toLowerCase()

      // 如果是 th，则与下一个 td 组成一组数据
      if (cellType === 'th') {
        const label = $cell.text().trim()
        let value = ''
        let span = 1

        // 查找下一个 td
        if (i + 1 < cells.length && cells[i + 1].tagName.toLowerCase() === 'td') {
          const $nextTd = $(cells[i + 1])
          value = $nextTd.text().trim()

          // 计算 span 值：colspan + 1 / 2，如果没有 colspan 则设为 1
          const colspan = parseInt($nextTd.attr('colspan') || '1')
          span = Math.ceil((colspan + 1) / 2)

          // 跳过下一个 td，因为已经处理过了
          i++
        }

        rowData.push({
          label,
          value,
          span
        })
      }
      // 如果是 td 且前面没有对应的 th，则单独处理
      else if (cellType === 'td') {
        const value = $cell.text().trim()
        const colspan = parseInt($cell.attr('colspan') || '1')
        const span = Math.ceil((colspan + 1) / 2)

        rowData.push({
          label: '',
          value,
          span
        })
      }
    }

    if (rowData.length > 0) {
      tableConfig.columns.push(...rowData)
    }
  })

  return tableConfig
}
